﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Views;
using IService.Login;
using Microsoft.Practices.ServiceLocation;
using Model.Login;
using System.Windows.Input;

namespace ViewModel.Login
{
    public class LoginViewModel:ViewModelBase
    {
        public LoginViewModel(ILoginService service)
        {
            _service = service;
            LoginCommand = new RelayCommand(Login, CanLogin);
        }
        #region 业务
        private ILoginService _service;
        #endregion
        #region 属性
        private string _userName;

        public string UserName
        {
            get { return _userName; }
            set
            {
                _userName = value;
                RaisePropertyChanged(() => UserName);
            }
        }
        private string _password;

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                RaisePropertyChanged(() => Password);
            }
        }
        #endregion

        #region 命令
        public ICommand LoginCommand { get; set; }
        private void Login()
        {
            var result = _service.GetLogin(UserName, Password);
            if (result.Item1 == null)
            {
                ServiceLocator.Current.GetInstance<IDialogService>().ShowError(result.Item2,"登陆失败",null,null);
            }
            else
            {
                MessengerInstance.Send<UserInfo>(result.Item1, "LoginViewModel_Login_Success");
            }
        }
        private bool CanLogin()
        {
            return !(string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password));
        }

        #endregion

        #region 方法

        #endregion
        #region 清理
        public override void Cleanup()
        {
            UserName = null;
            Password = null;
            base.Cleanup();
        }
        #endregion
    }
}
